package com.fruit.interceptor;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fruit.pojo.user.UserInfo;
import com.fruit.pojo.user.UserLogin;
import com.fruit.resolver.DefiniteException;
import com.fruit.service.user.UserManager;
import com.fruit.util.CustomUtil;
import com.fruit.util.MessagesCode;
import com.fruit.util.ResultInfo;
import com.fruit.util.ResultUtil;


public class WapSecurityInterceptor extends HandlerInterceptorAdapter {
	
	@Resource(name = "userService")
	private UserManager userService;
	
	@Value("${app.key}")
	private String key;
	
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		response.setContentType("text/html;charset=UTF-8");
		
		String signLogin = request.getParameter("signLogin");
		boolean isLogin = false;
		String loginId = "";
		if (StringUtils.isNotEmpty(signLogin)){
			System.out.println("登录验证开始");
			loginId = request.getParameter("loginId");
			String nonce = request.getParameter("nonce");
			String timestamp = request.getParameter("timestamp");
			UserLogin login = userService.getUserLoginById(Integer.parseInt(loginId));
			System.out.println(signLogin);
			if(login != null){
				Map<String, String> paramsO = new TreeMap<String, String>();
				paramsO.put("userName", login.getUserName());
				paramsO.put("pwd", login.getPwd());
				paramsO.put("nonce", nonce);
				paramsO.put("timestamp", timestamp);
				String mySign = CustomUtil.createSign(paramsO,key);
				System.out.println(mySign);
				if (StringUtils.equals(signLogin.toUpperCase(), mySign)) {
					isLogin = true;
				}
			}
			System.out.println("登录验证结束");
			if(isLogin){
				request.getSession().setAttribute("loginId", Integer.parseInt(loginId));
			}
		}	
		return true;
	}
	
	public ResultInfo initResult(String state, String code, String message,String url){
		ResultInfo ri = new ResultInfo();
		ri.setState(state);
		ri.setCode(code);
		ri.setMessage(message);
		ri.setUrl(url);
		return ri;
	}
}
